package org.rambadger.command.listeners;

import org.axonframework.eventhandling.annotation.EventHandler;
import org.axonframework.eventhandling.replay.ReplayAware;
import org.mongojack.DBUpdate;
import org.mongojack.JacksonDBCollection;
import org.rambadger.command.event.AssignmentAddedToTrack;
import org.rambadger.command.event.AssignmentCreated;
import org.rambadger.command.event.AssignmentRemovedFromTrack;
import org.rambadger.command.representation.Assignment;

import static org.rambadger.command.representation.Assignment.AssignmentId;

public class AssignmentListener implements ReplayAware {
    JacksonDBCollection<Assignment, AssignmentId> assignments;

    public AssignmentListener(JacksonDBCollection<Assignment, AssignmentId> assignments) {
        this.assignments = assignments;
    }
    @Override
    public void beforeReplay() {
        assignments.drop();
    }

    @Override
    public void afterReplay() {}

    @EventHandler void on(AssignmentCreated event) {
        assignments.insert(new Assignment(event.getPlatformId(), event.getAssignmentId(), event.getAssignmentName(), event.getDescription(), event.getSubmissionPoints(), event.getReviewPoints()));
    }

    @EventHandler void on(AssignmentAddedToTrack event){
        assignments.updateById(new AssignmentId(event.getPlatformId(),event.getAssignmentId()), DBUpdate.set("associatedTrack", event.getTrackId()));
    }

    @EventHandler void on(AssignmentRemovedFromTrack event){
        assignments.updateById(new AssignmentId(event.getPlatformId(),event.getAssignmentId()), DBUpdate.set("associatedTrack", null));
    }
}
